//
//  ContactDataObject.m
//  FlyingEagle
//
//  Created by Lj on 2017/3/20.
//  Copyright © 2017年 lj. All rights reserved.
//

#define DB_USER_TABLE @"contactData.sqlite"//数据库
#define DB_USER_LIST @"contactList"  //数据库biao


#import "ContactDataObject.h"
#import "FMDB.h"

@interface ContactDataObject()
@property (nonatomic, strong) FMDatabase *menuDB;

@end

@implementation ContactDataObject

+ (ContactDataObject *)shareInstance {
    static ContactDataObject *contactDataObject;
    if (!contactDataObject) {
        @synchronized(self) {
            if (!contactDataObject) {
                contactDataObject = [[ContactDataObject alloc] init];
            }
        }
    }
    return contactDataObject;
}

- (id)init {
    self = [super init];
    if (self) {
    }
    return self;
}

//连接数据库
- (void)createDateBase {
    //沙盒路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    //拼接 数据库的路径后面的数据库名字
    NSString *dataPath = [docPath stringByAppendingPathComponent:DB_USER_TABLE];
    NSLog(@"%@",dataPath);
    //示例化一个FMDB对象
    self.menuDB = [[FMDatabase alloc]initWithPath:dataPath];
    //调用open的时候 如果数据库不存在那么久会先创建在打开，如果存在就直接打开
    if ([self.menuDB open]) {
        //数据库一般只打开一次
        if (![self _isTableOK:DB_USER_LIST]) {
            [self _createTable];
        }
    }else {
        NSLog(@"create table error:%@",self.menuDB.lastErrorMessage);
    }
}

- (id)queryEasemobuserid:(id)data {
    if ([BHSettingUtil dataAndStringIsNull:data]) {
        return nil;
    }
    if ([data isKindOfClass:[NSString class]]) {
        return [self _queryData:data];
    }else {
        NSDictionary *dic = (NSDictionary *)data;
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE Easemobuserid = '%@'",DB_USER_LIST,dic[@"easemobuserId"]];
        FMResultSet *rs =[self.menuDB executeQuery:sql];
        while ([rs next]) {
            //存在
            [self _withTheData:data];
            return data;
        }
        [self _insertData:data];
        return data;
    }
    return nil;
}

//插入数据
- (void)insertData:(id)data {
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self queryEasemobuserid:data];
//    });
}

//删除数据
- (void)deleteData:(NSString *)easemobuserid {
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE Easemobuserid = %@",DB_USER_LIST,easemobuserid];
    BOOL isS = [self.menuDB executeUpdate:sql];
    if (!isS) {
        NSLog(@"insert into error :%@",self.menuDB.lastErrorMessage);
    }
}

#pragma mark - 内部方法
// 判断是否存在表
- (BOOL)_isTableOK:(NSString *)tableName {
    FMResultSet *rs = [self.menuDB executeQuery:@"SELECT count(*) as 'count' FROM sqlite_master WHERE type ='table' and name = ?", tableName];
    while ([rs next]) {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        if (count == 0) {
            return NO;
        }else {
            return YES;
        }
    }
    return NO;
}

//创建表
//用户表
- (void)_createTable {
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE %@  (primaryId integer primary key autoincrement not null,Easemobuserid text,userName text,logo text,Time text)",DB_USER_LIST];
    //执行SQL语句 成功返回yes 失败返回no
    BOOL isSucess = [self.menuDB executeUpdate:sql];
    if (isSucess) {
        NSLog(@"创建表成功");
    }else {
        NSLog(@"create table error:%@",self.menuDB.lastErrorMessage);
    }
}

//查询数据
- (id)_queryData:(NSString *)dataStr {
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE Easemobuserid = '%@'",DB_USER_LIST,dataStr];
    FMResultSet *rs =[self.menuDB executeQuery:sql];
    while ([rs next]) {
        NSString * userName = [rs stringForColumn:@"userName"];
        NSString * logo = [rs stringForColumn:@"logo"];
//        SGUserModel *model = [SGUserInfo getUserInfo];
//        if (![model.logo isEqualToString:logo]) {
//            logo = model.logo;
//        }
        NSDictionary *dic = @{@"easemobuserId":dataStr,@"userName":userName,@"logo":logo};
        return dic;
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:dataStr,@"easemobuserId",dataStr,@"userName",@"",@"logo", nil];
    return dic;
}

//插入数据
- (void)_insertData:(id)data {
    NSDictionary *dic = (NSDictionary *)data;
    UInt64 interval = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timeStr = [NSString stringWithFormat:@"%llu",interval];
    NSString *addSql = [NSString stringWithFormat:@"INSERT INTO %@(EasemobuserId,userName,logo,Time)values(?,?,?,?)",DB_USER_LIST];
    BOOL isS = [self.menuDB executeUpdate:addSql,dic[@"easemobuserId"],dic[@"userName"],dic[@"logo"],timeStr];
    if (!isS) {
        NSLog(@"insert into error :%@",self.menuDB.lastErrorMessage);
    }else {
        NSLog(@"添加数据成功");
    }
}

//更新数据
- (void)_withTheData:(id)data {
    NSDictionary *dic = (NSDictionary *)data;
    
//    NSString * logo = dic[@"logo"];
//    SGUserModel *model = [SGUserInfo getUserInfo];
//    if (![model.logo isEqualToString:logo]) {
//        logo = model.logo;
//    }
    
    UInt64 interval = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timeStr = [NSString stringWithFormat:@"%llu",interval];
    NSString * update = [NSString stringWithFormat:@"UPDATE %@ set userName = '%@',logo = '%@' , Time = '%@' where Easemobuserid = '%@'",DB_USER_LIST,dic[@"userName"],dic[@"logo"],timeStr,dic[@"easemobuserId"]];
    BOOL isSuccess = [self.menuDB executeUpdate:update];
    if (!isSuccess) {
        NSLog(@"update Failure");
    }
}

@end
